import os
import socket
import re
import time
import threading

"模块文件，通过发送指令到服务器，服务器接受之后，解压相应的文件"

# 读取serverip.txt文件，返回一个列表，每个元素的格式：ip:port
def get_server_lists():
    ip_lists = []
    rfiles = open('serverip.txt','r')
    rs = rfiles.readlines()
    for s in rs:
        s1 = s.replace('\n','')
        if not s1.startswith('#'):
            ip_lists.append(s1)
    return ip_lists

# 建立socket的会话，发送和接受指令
def tcp_socket_client(tcpsocket,ip,port,zipfilepath,unzippath):
    try:
        tcpsocket.connect((ip,port))

        #输入需要执行的选择，发送给服务端
        tcpsocket.send('2'.encode('utf-8'))

        # 接收服务器返回的消息
        rec_data = tcpsocket.recv(1024)
        #print(ip + ':' + rec_data.decode('gbk'))
        
        # 发送参数信息
        tcpsocket.send(zipfilepath.encode('utf-8'))
        tcpsocket.send(unzippath.encode('utf-8'))

        #接收服务器返回的状态信息
        rec_data1 = tcpsocket.recv(1024)
        print('%s:%s'%(ip,rec_data1.decode('gbk')))
        tcpsocket.close()

    except:
        print('%s:连接失败'%ip)

# 主函数，模块入口
def main():
    print(r'输入服务器端zip文件的路径，例如D:\\tdx\\base.zip')
    zipfilepath = input()
    print(r'输入zip文件解压后的路径，例如D:\\tdx\\')
    unzippath = input()

    # 多线程
    th_lists = []
    for s in get_server_lists():
        ip = re.split(':',s)[0]
        port = int(re.split(':',s)[1])
        try:
            tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            th = threading.Thread(target=tcp_socket_client,args=(tcp_socket,ip,port,zipfilepath,unzippath))
            th_lists.append(th)
        except:
            print('操作失败，socket将关闭！！')
            tcp_socket.close()

    for t in th_lists:
        t.start()
        time.sleep(0.5)
    
    for t in th_lists:
        t.join()
